import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { CreateCompanyDto } from "./dto/create-company.dto";
import { UpdateCompanyDto } from "./dto/update-company.dto";
import { Company } from "./company.entity";
import { dateNewFirst } from "src/utils/util";

@Injectable()
export class CompanyService {
  constructor(
    @InjectRepository(Company)
    private readonly companyRepository: Repository<Company>
  ) {}

  create(createCompanyDto: CreateCompanyDto): Promise<Company> {
    const company = new Company();
    Object.assign(company, createCompanyDto);
    return this.companyRepository.save(company);
  }

  async findAll(): Promise<[Company[], number]> {
    const ans = await this.companyRepository.findAndCount();
    const companies = ans[0].sort(dateNewFirst);
    return [companies, ans[1]];
  }

  findByName(name: string): Promise<Company | undefined> {
    return this.companyRepository.findOneOrFail({
      name,
    });
  }

  find(id: string): Promise<Company> {
    return this.companyRepository.findOneOrFail(id);
  }

  async update(
    id: string,
    updateCompanyDto: UpdateCompanyDto
  ): Promise<Company> {
    const company = await this.find(id);
    Object.assign(company, updateCompanyDto);
    return this.companyRepository.save(company);
  }

  async remove(company: string | Company) {
    const id = company instanceof Company ? company.id : company;
    const companyToRemove = await this.find(id);
    return await this.companyRepository.remove(companyToRemove);
  }
}
